<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="行政区划名称" prop="status">
        <el-select v-model="queryParams.code" placeholder="请选择新政区划" clearable>
          <el-option
            v-for="dict in regionList"
            :key="dict.code"
            :label="dict.name"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:menu:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="tableList"
      row-key="code"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="区划名称" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="code" label="区划编码" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="longitude" label="经度" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="latitude" label="纬度" :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:menu:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:menu:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改行政区划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级行政区划" prop="parentCode">
              <el-input v-if="form.parentCode =='0'" :value="form.name" disabled></el-input>
              <el-select v-else v-model="form.parentCode" placeholder="请选择新政区划" clearable style="width: 100%;">
                <el-option
                  v-for="row in regionList"
                  :key="row.code"
                  :label="row.name"
                  :value="row.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区划名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入区划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区划编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入区划编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
               <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入维度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="lifeStatus">
              <el-switch v-model="form.lifeStatus" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getRegionList,regionAdd,regionEdit,regionDelete} from '@/api/dataResources/monitorData/region.js'
export default {
  computed:{
    tableList(){
      if(!this.queryParams ||!this.queryParams.code){
        return this.regionList;
      }
      return this.regionList.filter(item => item.code == this.queryParams.code);
    },
  },
  data(){
    const validatorLongitude =  (rule, value, callback) => {
      const reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,15})|(\d|[1-9]\d|1[0-7]\d|0{1,15})|180\.0{0,15}|180)$/
      if(value === "") {
         callback(new Error('请输入经度'));
      }
      if(!reg.test(value)) {
        callback(new Error('经度范围：-180~180(保留小数点后六位)'));
      }
      callback()
    }
    const validatorLatitude = (rule, value, callback) => {
      const reg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,15}|90\.0{0,15}|[0-8]?\d{1}|90)$/
      if(value === "") {
         callback(new Error('请输入纬度'));
      }
      if(!reg.test(value)) {
        callback(new Error('纬度范围：-90~90(保留小数点后六位)'));
      }
      callback()
    }
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 菜单表格树数据
      regionList: [],
      // 是否展开，默认全部折叠
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        regionName: undefined,
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      formType:'',
      // 表单校验
      rules: {
        // parentCode: [
        //   { required: false, message: "上级行政区划能为空", trigger: "blur" }
        // ],
        name: [
          { required: true, message: "行政区划不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "区划编码不能为空", trigger: "blur" }
        ],
        longitude: [
          {validator: validatorLongitude, required: true, trigger: "blur" }
        ],
        latitude: [
          {validator: validatorLatitude, required: true, trigger: "blur" }
        ]
      }
    }
  },
  created(){
    this.getList();
  },
  methods:{
    resetQuery(){
      this.queryParams = {}
      this.getList()
    },
    handleQuery(){
      this.queryParams = {}
      this.getList()
    },
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    handleUpdate(row){
      this.initFormData(row,'edit');
      this.open = true
      this.title = "修改区划"
      this.formType = 'edit'
    },
    handleAdd(row = {}){
      this.initFormData(row,'add');
      this.open = true
      this.title = "添加区划"
      this.formType = 'add'
    },
    async handleDelete(row){
      await regionDelete(row.code)
      await this.getList();
    },
    initFormData(row = {},type){
      let parentCode = row.parentCode;
      if(parentCode && parentCode!='0'){
        let data = this.regionList.find(row => row.code ==parentCode);
        this.form.parentCode = data.code;
      } else{
        this.form.parentCode = '0';
      }
      console.log(row,this.form.parentCode)
      if(this.form.parentCode == '0'){
        if(type == 'add'){
          this.form.parentCode = row.code;
        }
      }
      if(type == 'edit'){
        this.form.name = row.name ||'';
        this.form.code = row.code || '';
        this.form.longitude = row.longitude ||'';
        this.form.latitude = row.latitude || '';
        this.form.lifeStatus = row.lifeStatus == '1';
      } else {
        this.form.name = '';
        this.form.code = '';
        this.form.longitude = '';
        this.form.latitude = '';
        this.form.lifeStatus = true;
      }
      this.form = {...this.form};
    },

    async saveByApi(){
      let apiFn = this.formType =='add'? regionAdd:regionEdit;
      let data = {...this.form};
      data.lifeStatus = this.form.lifeStatus ? '1':'0',
      await apiFn(data);
      await this.getList();
      this.open = false;
    },
    submitForm(){
      this.$refs["form"].validate((valid) =>{
        if(valid){
          this.saveByApi();
        }
      })
    },
    cancel(){
      this.open = false;
    },
    async getList(){
      this.loading = true;
      let res = await getRegionList('1');
      this.regionList = this.setTreeData(res.rows)
      this.loading = false;
    },
    setTreeData(rows){
      let data = [];
      let childRows = [];
      let map = {};
      let rowid = 0;
      for(let row of rows){
        if(row.parentCode == '0'){
          row.children = [];
          data.push(row);
          map[row.code] = rowid+'';
          rowid++;
        } else {
          childRows.push(row);
        }
      }
      for(let crow of childRows){
        let rowid = map[crow.parentCode];
        if(!rowid){
          data.push(crow)
        } else {
          if(data[+rowid]){
            if(!data[+rowid].children){
              data[+rowid].children = [];
            }
            data[+rowid].children.push(crow)
          } else {
            data.push(crow)
          }
        }
      }
      return data;
    }

  }
};
</script>

<style></style>
